package com.bwhx.eruler.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.bwhx.eruler.bean.Buyer;
import com.bwhx.eruler.bean.CScanData;
import com.bwhx.eruler.bean.Customer;
import com.bwhx.eruler.bean.Page;
import com.bwhx.eruler.service.CustomerService;
import com.bwhx.eruler.util.StringUtils;
import com.fasterxml.jackson.databind.DeserializationConfig;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * customer指的是被扫描者
 * @author Cuilitang
 *
 */
@Controller
public class CustomerController extends BaseController {
	
	@Autowired
	CustomerService customerService;

	@RequestMapping("/GetSCanDataInfoFormPage.ashx")
	public String goDownload(){
		return "/userscandownloadform.jsp";
	}
	
	@RequestMapping("/UpLoadSCandataFormPage.ashx")
	public String goUpload(){
		return "/uploadscandataformpage.jsp";
	}
	
	@SuppressWarnings("unchecked")
	@ResponseBody
	@RequestMapping(value = "/UpLoadSCandata.ashx",method={RequestMethod.POST})
	public Map upload(HttpServletRequest request){
		Map map = new HashMap();
		map.put("meg", "上传成功");
		map.put("status", "1");
		
		ObjectMapper objectMapper = new ObjectMapper();
		try{
				if(request.getHeader("Content-type").contains("json")){//苹果
			
				LinkedHashMap customerFieldMap = (LinkedHashMap) request.getAttribute("user_info");
				String jsonStr=customerFieldMap.toString();
				jsonStr = jsonStr.replace("=", ":").replace(" ", "").replace(":", "\":\"").replace(",", "\",\"").replace("{", "{\"").replace("}", "\"}");
				Customer customer = objectMapper.readValue(jsonStr, Customer.class);
				if(null!=customer.getRmac()){
					customer.setRmac(customer.getRmac().replace("_", ":"));
				}
				customer.setAddtime(System.currentTimeMillis()/1000);
				
		
				
			/*	String[] strArr = new String[]{customer.getUsername(),new Integer(customer.getSex()).toString(),new Integer(customer.getM_id()).toString(),customer.getRmac()};
				String[] strArr1 = new String[]{"用户名","性别","量体师ID","E尺MAC"};
				int mark = StringUtils.isEmpty(strArr);
				if(-1!=mark){
					map.put("meg", strArr1[mark]+"不能为空！");
					map.put("status", "0");
					return map;
				}
					*/		
				//因为传上来的cScanData json 与数据库存储的字段不一致，所以手动解析json存储到数据库
				LinkedHashMap scandataFieldMap = (LinkedHashMap) request.getAttribute("scandata_info");
				jsonStr=scandataFieldMap.toString().replace(" ", "");
				String[] propertiesArr = jsonStr.substring(1, jsonStr.length()-1).split(",");
				List<CScanData> cScanDataList =  new ArrayList<CScanData>();
				
				for(int i=0;i < propertiesArr.length;i++){
					String[] keyValue = propertiesArr[i].split("=");
					if(keyValue.length==2){
						cScanDataList.add(new CScanData(keyValue[0],keyValue[1],System.currentTimeMillis()/1000,2));
					}
				}	
				customer.setScanDatas(cScanDataList);
				
				//customerService 存储
				customerService.insert(customer);
			}else{//安卓
				
				map.put("meg", "不支持的 格式！");
				map.put("status", "0");
				return map;
				
				/*
				String user_info = request.getAttribute("user_info").toString();
				String scandata_info = request.getAttribute("scandata_info").toString();
				Customer customer = objectMapper.readValue(user_info, Customer.class);
				customer.setAddtime(System.currentTimeMillis()/1000);

					String[] strArr = new String[]{customer.getUsername(),new Integer(customer.getSex()).toString()};
					String[] strArr1 = new String[]{"用户名","性别"};
					int mark = StringUtils.isEmpty(strArr);
					if(-1!=mark){
						map.put("meg", strArr1[mark]+"不能为空！");
						map.put("status", "0");
						return map;
					}
				
				//因为传上来的cScanData json 与数据库存储的字段不一致，所以手动解析json存储到数据库
				
				String scandata_info_replace = scandata_info.replace(" ", "");
				String[] propertiesArr = scandata_info_replace.substring(1, scandata_info_replace.length()-1).split(",");
				List<CScanData> cScanDataList =  new ArrayList<CScanData>();
				
				for(int i=0;i < propertiesArr.length;i++){
					String[] keyValue = propertiesArr[i].replace("\"", "").split(":");
					if(keyValue.length==2){
						cScanDataList.add(new CScanData(keyValue[0],keyValue[1],System.currentTimeMillis()/1000,2));
					}
				}	
				customer.setScanDatas(cScanDataList);
				
				//customerService 存储
				customerService.insert(customer);
				*/
			}
	
		}catch(Exception e){
			log.error(getTrace(e));
			map.put("meg", "上传失败！");
			map.put("status", "0");
		}
	    return map;
	}
	
	@ResponseBody
	@RequestMapping(value = "/UpLoadSCandatabak.ashx",method={RequestMethod.POST})
	public Map uploadbak(@RequestParam("user_info") String user_info,@RequestParam("scandata_info") String scandata_info){
		Map map = new HashMap();
		map.put("meg", "上传成功");
		map.put("status", "1");
		
		ObjectMapper objectMapper = new ObjectMapper();
		try{
			Customer customer = objectMapper.readValue(user_info, Customer.class);
			customer.setAddtime(System.currentTimeMillis()/1000);
			//因为传上来的cScanData json 与数据库存储的字段不一致，所以手动解析json存储到数据库
			
			String scandata_info_replace = scandata_info.replace(" ", "");
			String[] propertiesArr = scandata_info_replace.substring(1, scandata_info_replace.length()-1).split(",");
			List<CScanData> cScanDataList =  new ArrayList<CScanData>();
			
			for(int i=0;i < propertiesArr.length;i++){
				String[] keyValue = propertiesArr[i].replace("\"", "").split(":");
				cScanDataList.add(new CScanData(keyValue[0],keyValue[1],System.currentTimeMillis()/1000,2));
			}	
			customer.setScanDatas(cScanDataList);
			
			//customerService 存储
			customerService.insert(customer);
		
	
		}catch(Exception e){
			log.error(getTrace(e));
			map.put("meg", "上传失败！");
			map.put("status", "0");
		}
	    return map;
	}
	
	@SuppressWarnings("unchecked")
	@ResponseBody
	@RequestMapping(value = "/GetSCanDataInfo.ashx",method={RequestMethod.POST})
	 public Map getetSCanDataInfo(HttpServletRequest request) {
		
		Map map = new HashMap();
		List<Customer> customerAtManager = new ArrayList<>();
		map.put("meg", "获取成功");
		map.put("status", "1");
		Object object = request.getAttribute("m_id");
		try{
			if(object!=null){
				if(object instanceof Integer){
					customerAtManager = customerService.findByMId((Integer)object);
				}else{
					customerAtManager = customerService.findByMId(new Integer((String)object).intValue());
				}
			}
			List<Map> userMaps = new ArrayList<>();
			for (Customer customer : customerAtManager) {
				log.info(customer.toString());
				log.info(customer.getScanDatas().toString());
				log.info("================");
				
				List<CScanData> scanDatas = customer.getScanDatas();
				
				Map scanDataMap = new HashMap();
				for (CScanData cScanData : scanDatas) {
					String typename = cScanData.getTypename();
					String shuzhi = cScanData.getShuzhi();
					scanDataMap.put(typename, shuzhi);
					
				}
				
				Map userMap = new HashMap();
				userMap.put("company", customer.getCompany());
				userMap.put("phone", customer.getPhone());
				userMap.put("remark", customer.getRemark());
				userMap.put("scandatetime", customer.getAddtime());
				userMap.put("sex", customer.getSex());
				userMap.put("userid", customer.getId());
				userMap.put("username", customer.getUsername());
				userMap.put("DataInfo", scanDataMap);
				
				userMaps.add(userMap);
			}
			map.put("SCanDataInfo", userMaps);
						
		}catch(Exception e){
			log.error(getTrace(e));
			map.put("meg", "获取失败！");
			map.put("status", "0");
		}
	    return map;  
	  }
	

	
	
	
	@ResponseBody
	@RequestMapping(value = "/bak.ashx",method={RequestMethod.POST})
	 public Map bak(@RequestParam("m_id") int m_id) {
		
		Map map = new HashMap();
		map.put("meg", "获取成功");
		map.put("status", "1");
		
		
		
		try{

						
		}catch(Exception e){
			log.error(getTrace(e));
			map.put("meg", "获取失败！");
			map.put("status", "0");
		}
	    return map;  
	  }
	
	
	
	@ResponseBody
	@RequestMapping(value = "/page.customerList.ashx")
	 public Map<String,Object> customerList(Integer page,Integer rows,Customer customer, @RequestBody String b) {
		 log.info(b);
		//每页的开始记录
        int start = (page-1)*rows;
        Page p = new Page(start,rows,customer);
		Map<String,Object> map = new HashMap<String,Object>();
		try{
			List<Customer> list = customerService.list(p);
			Integer count = customerService.count(customer);
			log.info(list);
			log.info(count);
			
			map.put("total",count);//total键 存放总记录数，必须的  
			map.put("rows",list);//rows键 存放每页记录 list 
			for (Customer customer1 : list) {
				log.info(customer1);
			}
			
		}catch(Exception e){
			log.error(getTrace(e));
			map.put("meg", "失败！");
			map.put("status", "0");
		}
		
	    return map;  
	  }
	
	@RequestMapping(value = "/page.customerdetails.ashx")
	 public ModelAndView BuyerDetails(@RequestParam String id){
		Customer customer = customerService.get(id);
		ModelAndView modelAndView = new ModelAndView("/rulerdata/customerdetails.jsp","customer",customer);
		
		return modelAndView;
	  }
	
	
	@ResponseBody
	@RequestMapping(value = "/page.scandatalist.ashx")
	 public Map<String,Object> scandataList(Integer page,Integer rows,Integer userid, @RequestBody String b) {
		 log.info(b);
		//每页的开始记录
        int start = (page-1)*rows;
        Page p = new Page(start,rows,userid);
		Map<String,Object> map = new HashMap<String,Object>();
		try{
			List<CScanData> list = customerService.listScanData(p);
			Integer count = customerService.countScanData(userid);
			log.info(list);
			log.info(count);
			
			map.put("total",count);//total键 存放总记录数，必须的  
			map.put("rows",list);//rows键 存放每页记录 list 
			for (CScanData scandata : list) {
				log.info(scandata);
			}
			
		}catch(Exception e){
			log.error(getTrace(e));
			map.put("meg", "失败！");
			map.put("status", "0");
		}
		
	    return map;  
	  }
	
	@SuppressWarnings("unchecked")
	@ResponseBody
	@RequestMapping(value = "/newUpLoadSCandata.ashx",method={RequestMethod.POST})
	public Map uploadNew(HttpServletRequest request){
		Map map = new HashMap();
		
		
		
		ObjectMapper objectMapper = new ObjectMapper();
		try{
				if(request.getHeader("Content-type").contains("json")){//苹果
			
					LinkedHashMap customerFieldMap = (LinkedHashMap) request.getAttribute("user_info");
					
					String writeValueAsString = objectMapper.writeValueAsString(customerFieldMap);
					log.info(writeValueAsString);
					/*String jsonStr=customerFieldMap.toString();
					log.info(jsonStr);
					jsonStr = jsonStr.replace("=", ":").replace(" ", "").replace(":", "\":\"").replace(",", "\",\"").replace("{", "{\"").replace("}", "\"}");
					*/
					Customer customer = objectMapper.readValue(writeValueAsString, Customer.class);
					String uuid = customer.getcUUID();
					boolean uUIDisEmpty = StringUtils.isEmpty(uuid);
					List<Customer> customers = new ArrayList<>();
					if(!uUIDisEmpty&&uuid.length()>=32){
						customers = customerService.findByUUID(customer.getcUUID());
					}
					
					if(customers.size()==1){
						
						customerService.delUser(customers.get(0).getId());
						customerService.delScanData(customers.get(0).getId());
						
					}

					if(null!=customer.getRmac()&&!"".equals(customer.getRmac())){
						customer.setRmac(customer.getRmac().replace("_", ":"));
					}
					if(null!=customer.getErmac()&&!"".equals(customer.getErmac())){
						customer.setErmac(customer.getErmac().replace("_", ":"));
					}
					if(null!=customer.getEbmac()&&!"".equals(customer.getEbmac())){
						customer.setEbmac(customer.getEbmac().replace("_", ":"));
					}
					if(null!=customer.getEsmac()&&!"".equals(customer.getEsmac())){
						customer.setEsmac(customer.getEsmac().replace("_", ":"));
					}
					if(null!=customer.getEamac()&&!"".equals(customer.getEamac())){
						customer.setEamac(customer.getEamac().replace("_", ":"));
					}
					customer.setAddtime(System.currentTimeMillis()/1000);
					
					String jsonStr = new String();
	
					//因为传上来的cScanData json 与数据库存储的字段不一致，所以手动解析json存储到数据库
					LinkedHashMap<String,LinkedHashMap<String,String>> scandataMap = (LinkedHashMap<String,LinkedHashMap<String,String>>) request.getAttribute("scandata_info");
					List<CScanData> cScanDataList =  new ArrayList<CScanData>();
					for (Map.Entry<String, LinkedHashMap<String,String>> entry : scandataMap.entrySet()) {
						String key = entry.getKey();
						LinkedHashMap<String,String> scandataFieldMap = entry.getValue();
						jsonStr=scandataFieldMap.toString().replace(" ", "");
						String[] propertiesArr = jsonStr.substring(1, jsonStr.length()-1).split(",");
						for(int i=0;i < propertiesArr.length;i++){
							String[] keyValue = propertiesArr[i].split("=");
							if(keyValue.length==2){
								cScanDataList.add(new CScanData(key,keyValue[0],keyValue[1],System.currentTimeMillis()/1000,2));
							}
						}
					
					} 
					
					customer.setScanDatas(cScanDataList);
					
					//customerService 存储
					customerService.insert(customer);
					
					map.put("status", "1");
					map.put("meg", "上传成功");
					return map;
				
					
			}else{//安卓
				
				map.put("meg", "不支持的 格式！");
				map.put("status", "0");
				return map;
			}
	
		}catch(Exception e){
			log.error(getTrace(e));
			map.put("meg", "上传失败！");
			map.put("status", "0");
		}
	    return map;
	}
	
 	@ResponseBody
	@RequestMapping(value = "/customerLogon.ashx",method={RequestMethod.POST})
	 public Map<String,Object> customerLogon(HttpServletRequest request) {
		
		Map<String,Object> resultMap = new HashMap<String,Object>();
		List<Customer> resultCustomer = new ArrayList<Customer>();
		Object object = request.getAttribute("customerphone");
		try{
			if(object!=null){
					resultCustomer = customerService.findByPhone(object.toString());
				
			}
			
			if(resultCustomer.size()==0){
				resultMap.put("msg", "用户名或者密码错误！");
				resultMap.put("status", "0");
				return resultMap;
			}
 			
			Customer customer = resultCustomer.get(0);
			List<CScanData> scanDatas = customer.getScanDatas();
			
			Map<String,Object> scanDataMap = new HashMap<String,Object>();
			for (CScanData cScanData : scanDatas) {
				String typename = cScanData.getTypename();
				String shuzhi = cScanData.getShuzhi();
				scanDataMap.put(typename, shuzhi);
				
			}
			
			Map<String,Object> userMap = new HashMap<String,Object>();
			userMap.put("company", customer.getCompany());
			userMap.put("phone", customer.getPhone());
			userMap.put("remark", customer.getRemark());
			userMap.put("scandatetime", customer.getAddtime());
			userMap.put("sex", customer.getSex());
			userMap.put("userid", customer.getId());
			userMap.put("username", customer.getUsername());
			userMap.put("DataInfo", scanDataMap);
			
				 
 			
			
			resultMap.put("data", userMap);
			resultMap.put("msg", "获取成功");
			resultMap.put("status", "1");
						
		}catch(Exception e){
			log.error(getTrace(e));
			resultMap.put("msg", "登陆失败！");
			resultMap.put("status", "0");
		}
	    return resultMap;  
	  }
 	
 	@ResponseBody
	@RequestMapping(value = "/page.everyone.phoneScandataList.ashx")
	 public Map<String,Object> phoneScandataList(Customer customer) {
		
		Map<String,Object> resultMap = new HashMap<String,Object>();
		resultMap.put("status", "0");
		List<Customer> customerByPhone = customerService.find(customer);
		Customer latestCustomer = null;
		if(customerByPhone.size()==0){
			return resultMap;
		}else{
			latestCustomer = customerByPhone.get(0);
			if(customerByPhone.size()>1){
				for (int i = 0; (i+1) < customerByPhone.size(); i++) {

					if(customerByPhone.get(i).compareTo(customerByPhone.get(i+1))==-1){
						latestCustomer = customerByPhone.get(i+1);
					
					}
				}
			}
		} 
		//每页的开始记录
        Page p = new Page(0,0,latestCustomer.getId());
		List<CScanData> list = customerService.listScanData(p);
		resultMap.put("data", list);
		resultMap.put("customer", latestCustomer);
		resultMap.put("status", "1");
	    return resultMap;  
	  }
	
	
	@ResponseBody
	@RequestMapping(value = "/page.everyone.sceneidPhone.ashx")
	 public String sceneidScandataList(String sceneid) {
		
		String phone = customerService.findPhoneBySceneid(sceneid);
		return phone;
		
		
		
	}
	
 	/**
 	 * 微信后台用，根据手机查历史记录，未完成
 	 * @param customer
 	 * @return
 	 */
	@ResponseBody
	@RequestMapping(value = "/page.phoneHistoryList.ashx")
	 public Map<String,Object> phoneHistoryList(Customer customer) {
		
		Map<String,Object> resultMap = new HashMap<String,Object>();
		resultMap.put("status", "0");
		List<Customer> customerByPhone = customerService.find(customer);
 		if(customerByPhone.size()==0){
			return resultMap;
		}else{
			for (Customer customer2 : customerByPhone) {
				//TODO
			}
			resultMap.put("data", "1");
		}
		resultMap.put("status", "1");
	    return resultMap;  
	  }
	
	

	
	
}
